extends Node

@export var max_speed: int = 40
@export var acceleration: float = 5

var velocity = Vector2.ZERO


func accelerate_to_player():
	var owner_node2d = owner as Node2D
	if owner_node2d == null:
		return
	
	var player = get_tree().get_first_node_in_group("player") as Node2D
	if player == null:
		return
	
	var direction = owner_node2d.global_position.direction_to(player.global_position)
	accelerate_in_direction(direction)


func decelerate_to_zero(_acceleration: float = acceleration):
	accelerate_in_direction(Vector2.ZERO, 0, _acceleration)


func accelerate_in_direction(direction: Vector2, speed: float = max_speed, _acceleration: float = acceleration):
	var desired_velocity = direction * speed
	velocity = velocity.lerp(desired_velocity, 1 - exp(-_acceleration * get_physics_process_delta_time()))
	move(owner)


func move(character_body: CharacterBody2D):
	character_body.velocity = velocity
	character_body.move_and_slide()
	# 有可能characterbody移动之后碰撞到东西停下来了，所以同步一下velocity
	velocity = character_body.velocity
